﻿using System;
using UnityEngine;
using UnityEngine.UI;
using static System.Net.Mime.MediaTypeNames;

public class NetworkImage : MonoBehaviour
{
    public RawImage photo;
    public string url { get; set; }

    Texture2D m_Texture2D;
    public Texture2D texture2D => m_Texture2D;

    float iconSize;

    void Awake()
    {
        if (photo == null)
            photo = GetComponent<RawImage>();
        if (iconSize <= 0)
        {
            if(photo.rectTransform.rect.width > photo.rectTransform.rect.height)
                iconSize = photo.rectTransform.rect.width;
            else
                iconSize = photo.rectTransform.rect.height;
        }
    }

    void PreInit()
    {
        if (photo == null)
            photo = GetComponent<RawImage>();

        if (m_Texture2D)
            DestroyImmediate(m_Texture2D);
        m_Texture2D = null;

        if (iconSize <= 0)
            iconSize = photo.rectTransform.rect.height;

        photo.texture = null;//TODO.显示加载中图片
    }

    public void InitWithData(Tex tex)
    {
        PreInit();
        if (!string.IsNullOrEmpty(url))
        {
            m_Texture2D = UnityFunctions.GetTextureWithData(tex);//, (tex) =>
            UnityFunctions.SetRawImage(photo, m_Texture2D, iconSize);
        }
    }

    public void Init(string url,Action onInitIconEnd = null)
    {
        PreInit();
        if (!string.IsNullOrEmpty(url))
        {
            UnityFunctions.GetTextureWithUrl(url, (tex) =>
            {
                m_Texture2D = tex;

                UnityFunctions.SetRawImage(photo, tex, iconSize);

                onInitIconEnd?.Invoke();
            });
        }
    }

    public Vector2 SetImgSize(float size)
    {
        iconSize = size;
        //GameDebug.LogError($"{name} SetImgSize:{size} {m_Texture2D != null}");

        return UnityFunctions.SetRawImage(photo, m_Texture2D, iconSize);
    }

    void OnDestroy()
    {
        if (m_Texture2D)
            DestroyImmediate(m_Texture2D);

    }
}
